//
//  DynamicAnalysisVC.m
//  SelfDriving
//
//  Created by apple on 16/1/17.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "DynamicAnalysisVC.h"
#import "DynamicCell.h"
#import "BusinessService+WD.h"
@interface DynamicAnalysisVC ()<UITableViewDataSource,UITableViewDelegate,BaseTableDetelage,UICollectionViewDelegate,UICollectionViewDataSource,UITextViewDelegate,KYExpressionInputViewDelegate>
@property (weak, nonatomic) IBOutlet BaseTable *table;
@end

@implementation DynamicAnalysisVC
{
    NSMutableArray *data;
    UILabel *notlabel;
    int cont;
    KYExpressionInputView *inputView;
    BOOL isUp;
    int isReplySingle;//是否回复单人
    NSMutableDictionary *ReplySingle;//回复单人集合
    DTModel *huifumsg;
    MPMoviePlayerController *moviePlayer;
    
}
- (void)viewDidLoad {
    self.navigationController.navigationBarHidden = NO;
    [super viewDidLoad];
    _table.bdelegate = self;
    data = [[NSMutableArray alloc]init];
    CGRect c = _table.frame;
    c.size.height = c.size.height-[AppDelegate shareDelegate]._tableBarController.tabBar.frame.size.height;
    _table.frame = c;
    
    //xhw2018-1-16加：
    [self initData:1];
}
-(void)initData:(int)index{
    _table.backgroundColor = colorBG ;
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:[NSNumber numberWithInt:index] forKey:@"page"];
    [[BusinessService shareInstance]dynaimc_statistics:dic success:^(id result) {
        data = [_table result:result olddata:data index:index];
        if (notlabel) {
            [notlabel removeFromSuperview];
        }
        notlabel = (UILabel *)[_table notData];
        if (data.count == 0) {
            [self.view addSubview:notlabel];
        }
        [_table reloadData];
        _table.header.hidden = YES;
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return data.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    cell.backgroundColor = colorBG;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    DTModel *model = [data objectAtIndex:indexPath.section];
    UIView *bgview= [[UIView alloc]initWithFrame:CGRectMake(10, 20, SCRE_WIDTH-20, 300)];
    //基础UI
    int b = [_table Basics:cell dtmodel:model bgview:bgview];
    //个人头像按钮
    UIButton *headbtn = [[UIButton alloc]initWithFrame:CGRectMake(20, 10, 45, 45)];
    headbtn.tag = indexPath.section;
    [headbtn addTarget:self action:@selector(toIndividualAction:) forControlEvents:UIControlEventTouchUpInside];
    [bgview addSubview:headbtn];
    
    
    int file = 0;
    //附件
    if (model.attachment.count != 0) {
        file = [_table Attachment:cell dtmodel:model bgview:bgview];
        NSMutableDictionary *dic = [model.attachment lastObject];
        NSString *url = [dic objectForKey:@"path"];
        url = [url substringFromIndex:url.length-3];
        //附件按钮
        BaseButton *headbtn = [[BaseButton alloc]initWithFrame:CGRectMake(0, 45, SCRE_WIDTH-20, 180)];
        headbtn.tag = indexPath.section;
        if ([url isEqualToString:@"mp4"]) {
            if (!model.iskuaipai) {
                [headbtn setImage:[UIImage imageNamed:@"图标---视频播放"] forState:UIControlStateNormal];
            }

        }
        [headbtn addTarget:self action:@selector(imgTouchAction:) forControlEvents:UIControlEventTouchUpInside];
        [bgview addSubview:headbtn];
    }
    //内容
    MLEmojiLabel *elable = [[MLEmojiLabel alloc]initWithFrame:CGRectMake(0, b+file, SCRE_WIDTH-20, 60)];
//    [ValidateHelper ReplaceMLEmojiLabel:model.title emojilable:elable];
    [ValidateHelper ReplaceMLEmojiLabel:@"" emojilable:elable];

    [bgview addSubview:elable];
    int conth = elable.frame.size.height;
    //内容下线
    UILabel *ine = [[UILabel alloc]initWithFrame:CGRectMake(10, b+file+conth,SCRE_WIDTH-40,0.5)];
    ine.backgroundColor = colorBG;
    [bgview addSubview:ine];
    //赞
    int zanh= 0;
    if (model.zanlist.count!=0) {
        int ih = (SCRE_WIDTH-20)/30;
        float  yu = (float)model.zanlist.count/ih;
        int y = ceilf(yu);
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        UICollectionView *view = [[UICollectionView alloc]initWithFrame:CGRectMake(0, b+file+conth+1, SCRE_WIDTH-20, y*35) collectionViewLayout:flowLayout];
        view.scrollEnabled = NO;
        view.backgroundColor = [UIColor clearColor];
        [view registerClass:[zanCell class] forCellWithReuseIdentifier:@"zanCell"];
        
        view.tag = indexPath.section;
        view.delegate = self;
        view.dataSource = self;
        [bgview addSubview:view];
        zanh = y*35;
        ine.hidden = YES;
    }
    // 留言
    int ly = b+file+zanh+conth+5;
    int y = ly;
    int liuh=0;
    if (model.commentlist.count!=0) {
        liuh=0;
        y = ly;
        for (int i = 0; i<model.commentlist.count; i++) {
            NSMutableDictionary *dic = [model.commentlist objectAtIndex:i];
            int x =0;
            NSString *rname = [dic objectForKey:@"reply_nickname"];
            if (rname.length !=0) {
                x = 35;
            }
            UIImageView *head = [[UIImageView alloc]initWithFrame:CGRectMake(10+x, y, 35, 35)];
            [head sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"headsmall"]]
                    placeholderImage:[UIImage imageNamed:@"mrtx"]];
            head.layer.cornerRadius = 35/2;
            head.clipsToBounds = YES;
            CGSize n = [ValidateHelper sizeOfText:x!=0?[NSString stringWithFormat:@"%@回复%@",[dic objectForKey:@"nickname"],[dic objectForKey:@"reply_nickname"]]:[dic objectForKey:@"nickname"]  theFont:[UIFont systemFontOfSize:13]];
            [bgview addSubview:head];
            int j = x!=0?x-15:0;
            BaseButton *btn = [[BaseButton alloc]initWithFrame:CGRectMake(45+j, y,n.width*2, 30)];
            [btn addTarget:self action:@selector(SingleReplyActino:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag = indexPath.section;
            btn.index = i;
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn setTitle:x!=0?[NSString stringWithFormat:@"%@回复%@",[dic objectForKey:@"nickname"],[dic objectForKey:@"reply_nickname"]]:[dic objectForKey:@"nickname"] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:15];
            [bgview addSubview:btn];
            
            
            CGSize size = [ValidateHelper sizeOfText:[dic objectForKey:@"content"] theFont:[UIFont systemFontOfSize:13] theWidth:bgview.frame.size.width];
            //计算表情高度
          
            MLEmojiLabel * _emojiLabel = [MLEmojiLabel new];
            _emojiLabel.numberOfLines = 0;
            _emojiLabel.font = [UIFont systemFontOfSize:16.0f];
            _emojiLabel.backgroundColor = [UIColor clearColor];
            _emojiLabel.lineBreakMode = NSLineBreakByWordWrapping;
            _emojiLabel.textColor = [UIColor blackColor];
            
            _emojiLabel.textInsets = UIEdgeInsetsMake(5, 10, 0, 10);
            
            _emojiLabel.isNeedAtAndPoundSign = YES;
            _emojiLabel.disableEmoji = NO;
            
            _emojiLabel.lineSpacing = 3.0f;
            
            _emojiLabel.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
            _emojiLabel.customEmojiRegex = @"\\[[emoji_[0-9]{1,3}]+\\]";
            _emojiLabel.customEmojiPlistName = @"expressionImage_custom.plist";
            [_emojiLabel setText:[dic objectForKey:@"content"]];
            
            [bgview addSubview:_emojiLabel];
            CGRect g = _emojiLabel.frame;
            g.size.height = ([_emojiLabel preferredSizeWithMaxWidth:SCRE_WIDTH].height+25.0f*2);
            g.origin.y =  15;
            g.size.width = SCRE_WIDTH-10;
            g.origin.x = 0;
            _emojiLabel.frame = g;
//content.attributedText = [[NSAttributedString alloc]initWithString:[dic objectForKey:@"content"] attributes:attributes];
//            
//            content.userInteractionEnabled = NO;
//            content.backgroundColor = [UIColor clearColor];
//            content.font = [UIFont systemFontOfSize:14];
//            [ValidateHelper ReplaceExpression:[dic objectForKey:@"content"] label:content size:15 isr:YES];
//            
//            [bgview addSubview:content];
            y = y+_emojiLabel.frame.size.height;
        }
        liuh =  y - ly;
    }
    //底部
    int bottom = b+file+zanh+conth+liuh;
    //    UIButton *sharebtn = [[UIButton alloc]initWithFrame:CGRectMake(10, bottom, 40, 30)];
    //    [sharebtn setImage:[UIImage imageNamed:@"fx"] forState:UIControlStateNormal];
    //    [sharebtn setTitle:model.sharecount forState:UIControlStateNormal];
    //    [sharebtn setTitleColor:colorGrey forState:UIControlStateNormal];
    //    sharebtn.titleLabel.font = [UIFont systemFontOfSize:13];
    //    [bgview addSubview:sharebtn];
    //
    //    UIButton *zanbtn = [[UIButton alloc]initWithFrame:CGRectMake(50, bottom, 40, 30)];
    //    [zanbtn setImage:[UIImage imageNamed:@"zan"] forState:UIControlStateNormal];
    //    [zanbtn setTitleColor:colorGrey forState:UIControlStateNormal];
    //    zanbtn.titleLabel.font = [UIFont systemFontOfSize:13];
    //    [zanbtn setTitle:model.zancount forState:UIControlStateNormal];
    //    zanbtn.tag = indexPath.section;
    //    [zanbtn addTarget:self action:@selector(praiseAction:) forControlEvents:UIControlEventTouchUpInside];
    //    [bgview addSubview:zanbtn];
    //
    //    BaseButton *plbtn = [[BaseButton alloc]initWithFrame:CGRectMake(100, bottom, 40, 30)];
    //    [plbtn setImage:[UIImage imageNamed:@"pl"] forState:UIControlStateNormal];
    //    [plbtn setTitleColor:colorGrey forState:UIControlStateNormal];
    //    plbtn.titleLabel.font = [UIFont systemFontOfSize:13];
    //    plbtn.tag = indexPath.section;
    //    [plbtn setTitle:model.commentcount forState:UIControlStateNormal];
    //    [plbtn addTarget:self action:@selector(toReplyAction:) forControlEvents:UIControlEventTouchUpInside];
    //    [bgview addSubview:plbtn];
    //
    //    UILabel *distance = [[UILabel alloc]initWithFrame:CGRectMake((SCRE_WIDTH-20)-90, bottom,80, 30)];
    //    distance.text = [ValidateHelper DistanceFormat:model.distance];
    //    distance.font = [UIFont systemFontOfSize:14];
    //    distance.textColor = colorGrey;
    //    distance.textAlignment = NSTextAlignmentRight;
    //    [bgview addSubview:distance];
    
    CGRect bg = bgview.frame;
    bg.size.height = bottom + 20;
    bgview.frame = bg;
    
    CGRect cl =  cell.frame;
    cl.size.height = bottom + 40;
    cell.frame = cl;
    return cell;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    DTModel *model = [data objectAtIndex:collectionView.tag];
    return  model.zanlist.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DTModel *model = [data objectAtIndex:collectionView.tag];
    NSMutableDictionary *dic = [model.zanlist objectAtIndex:indexPath.row];
    
    zanCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"zanCell" forIndexPath:indexPath];
    UIImageView *head = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    head.layer.cornerRadius = 35/2;
    head.clipsToBounds = YES;
    [head sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"headsmall"]]
            placeholderImage:[UIImage imageNamed:@"mrtx"]];
    [cell.contentView addSubview:head];
    
    UIImageView *bq = [[UIImageView alloc]initWithFrame:CGRectMake(35/2, 35/2, 20, 20)];
    bq.image = [UIImage imageNamed:@"emoji_52"];
    [head addSubview:bq];
    
    return cell;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 5, 0, 5);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size = CGSizeMake(32, 32);
    return size;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
 
#pragma mark 图片详情
-(void)imgTouchAction:(BaseButton *)sender{
    DTModel *msg = [data objectAtIndex:sender.tag];
    NSString *url;
    NSMutableDictionary *dic = [msg.attachment lastObject];
    url = [dic objectForKey:@"path"];
    if (![ValidateHelper isHttpHead:url]) {
        url = [NSString stringWithFormat:@"%@%@",img_Url,url];
    }
    if ([dic objectForKey:@"path"]) {
        if([url rangeOfString:@"mp4"].location !=NSNotFound){//_roaldSearchText
            [self Plays:url];
        }else{
            [self EnlargePicAction:msg];
        }}
}
#pragma mark 视频播放
-(void)Plays:(NSString *)not{
    NSURL *url = [NSURL URLWithString:not];
    moviePlayer = [ValidateHelper bofang:url];
    [self.view addSubview:moviePlayer.view];
    self.navigationController.navigationBarHidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playVideoFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
    
 }
#pragma  mark 视频播放注销监听
- (void)playVideoFinished:(NSNotification *)theNotification{
    // 取消监听
    self.navigationController.navigationBarHidden = NO;
    [[NSNotificationCenter defaultCenter]
     removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
    // 将视频视图从父视图中删除
    [moviePlayer.view removeFromSuperview];
}
#pragma mark 图片放大
-(void)EnlargePicAction:(DTModel *)not{
    NSMutableArray  *imgdata = [[NSMutableArray alloc]init];
    DTModel *msg = not;
    for (int i= 0;i<msg.attachment.count; i++) {
        ZLPhotoPickerBrowserPhoto *photo = [[ZLPhotoPickerBrowserPhoto alloc] init];
        NSString *url = [[msg.attachment objectAtIndex:i] objectForKey:@"path"];
        if (![ValidateHelper isHttpHead:url]) {
            url = [NSString stringWithFormat:@"%@%@",img_Url,url];
        }
        photo.photoURL = [NSURL URLWithString:url];
        [imgdata addObject:photo];
    }
    
    // 图片游览器
    ZLPhotoPickerBrowserViewController *pickerBrowser = [[ZLPhotoPickerBrowserViewController alloc] init];
    // 数据源/delegate
    //    pickerBrowser.delegate = self;
    pickerBrowser.status = UIViewAnimationAnimationStatusFade;
    
    // 数据源可以不传，传photos数组 photos<里面是ZLPhotoPickerBrowserPhoto>
    pickerBrowser.photos = imgdata;
    // 是否可以删除照片
    pickerBrowser.editing = NO;
    // 当前选中的值
    pickerBrowser.currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    // 展示控制器
    [pickerBrowser showPickerVc:self];
    
}
- (IBAction)backActino:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
